package cn.flant.io.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ObjectMessageHandler extends MessageHandler {
	private ObjectInputStream reader;
	private ObjectOutputStream writer;
	private int writeCount;

	@Override
	public void onConnected(Socket socket) throws IOException {
		writer = new ObjectOutputStream(socket.getOutputStream());
		reader = new ObjectInputStream(socket.getInputStream());
		writeCount = 0;
	}

	@Override
	public Object readMessage() throws IOException {
		try {
			return reader.readObject();
		} catch (ClassNotFoundException e) {
			return new IOException("ClassNotFoundException: " + e.getMessage(), e);
		}
	}

	@Override
	public void sendMessage(Object message) throws IOException {
		if (writeCount >= 100) {
			writer.reset();
			writeCount = 0;
		} else {
			writeCount++;
		}
		writer.writeUnshared(message);
		writer.flush();
	}

	@Override
	public void onClosed() {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
			}
			reader = null;
		}
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
			}
			writer = null;
		}
	}

}
